//
//  ZJComposeViewController.swift
//  Webo
//
//  Created by 曾静 on 16/7/3.
//  Copyright © 2016年 qq. All rights reserved.
//

import UIKit

class ZJComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
         setNav()
        
        setupUI()

    }
    
    func  setNav(){
        
    view.backgroundColor = UIColor.whiteColor()
        
       navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancel")
        
      navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
        
        navigationItem.rightBarButtonItem?.enabled = false
    }
    
    func setupUI(){
        
        view.addSubview(composeTextView)
        
        view.addSubview(composeToolBar)
        
//        view.addSubview(emtionView)
        
        composeTextView.addSubview(composePictureView)
        
        composePictureView.clourse = {
            self.selectImages()
        }
        
        //添加titleView
        navigationItem.titleView = titleView
        
        //添加约束
        composeTextView.snp_makeConstraints { (make) -> Void in
            
           make.edges.equalTo(view).offset(UIEdgeInsetsZero)
            
        }
        
        composeToolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        composePictureView.snp_makeConstraints { (make) -> Void in
            
            make.leading.equalTo(self.composeTextView).offset(10)
            
            make.top.equalTo(self.composeTextView).offset(100)
            
            make.size.equalTo(CGSize(width: SCREENW - 20, height: SCREENW - 20))
        }
        //记得循环引用的问题
        composeToolBar.clourse = { [weak self] (tagType:ComposeTagType)->() in
            
            switch tagType {
            case .Picture:
                self?.selectImages()
                print("图片")
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emotion:
                print("表情")
                self?.selctedKeyBoard()
            case .Add:
                print("+")
                
            }
            
            
        }
        
//        emtionView.snp_makeConstraints { (make) -> Void in
//            make.leading.trailing.bottom.equalTo(view)
//            make.height.equalTo(216)
//        }
        
        //注册通知,监听键盘的change
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardDidChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }
    
    func keyboardDidChangeFrame(noti:NSNotification){
        
        let rect = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        
        composeToolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(-SCREENH + rect.origin.y)
        }
        UIView.animateWithDuration(0.1) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    //注册通知记得移除通知
    deinit{
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
        
    }
 
    private lazy var titleView:UILabel = {
    
    let lab = UILabel()
        
    let name =  ZJUserInfoTools.shareUserInfo.userAccount?.screen_name ?? ""

    let str = "发微博\n\(name)"
     
    var attrText = NSMutableAttributedString(string: str)
        
    let range = (str as NSString).rangeOfString("发微博")
        
    let range1 = (str as NSString).rangeOfString(name)//本身就是字符串加什么""
    
     attrText.addAttributes([NSForegroundColorAttributeName:ThemeColor,NSFontAttributeName:UIFont.systemFontOfSize(13)], range: range1)
    
    attrText.addAttributes([NSForegroundColorAttributeName:UIColor.grayColor(),NSFontAttributeName:UIFont.systemFontOfSize(17)], range: range)
        
    lab.attributedText = attrText
        
        lab.numberOfLines = 0
        lab.textAlignment = .Center
        
    lab.sizeToFit()
     
    return lab
        
    
    }()

    
    private lazy var composeToolBar:ZJComposeToolBarView = ZJComposeToolBarView()

    //懒加载控件,将pictureView添加到textView上面,实现滚动
    private lazy var composePictureView:ZJComposePictureView = ZJComposePictureView()
    
    private lazy var composeTextView:ZJComposeTextView = {
        
        let textView = ZJComposeTextView()
        
        textView.textColor = UIColor.blackColor()
        
        textView.alwaysBounceVertical = true//允许竖直方向的弹性
        
        //为了当textView点击的时候lab上面的文字消除,我们实现textView的代理方法
        textView.delegate = self
        
        textView.placeholder = "我同桌又骂人了我同桌又骂人了我同桌又骂人了我同桌又骂人了我同桌又骂人了我同桌又骂人了我同桌又骂人了我同桌又骂人了"
        textView.font = UIFont.systemFontOfSize(20)
        
        return textView
        
        
    }()
  
    
    //懒加载控件
    private lazy var  emtionView:ZJEmtionView = {
        
        let view = ZJEmtionView()
        
        view.width = SCREENW
        
        view.height = 216
        
        view.x = 0

        view.y = 0
        
        return view
    }()

    private lazy var picker:UIImagePickerController = UIImagePickerController()
    //取消
    @objc private func cancel(){
    
        //头取消之前失去第一响应者
        self.resignFirstResponder()
        self.dismissViewControllerAnimated(false, completion: nil)
    }
   
    //发送微博,调用微博的接口
    @objc private func send(){
        
        if composePictureView.imageList.count > 0{
            
            ZJNetWorkTools.shareTools.uploadUserDataWithOnePicture(composeTextView.text!, imageList: composePictureView.imageList, sucess: { (response) -> () in
                
                  print("图片微博发送成功")
                
                }, fail: { (error) -> () in
                    
                     print("图片微博发送失败")
            })
            
        }else{
            
            ZJNetWorkTools.shareTools.updateUserData(composeTextView.text!) { (response, error) -> () in
                if error == nil{
                    print("微博发送失败")
                    return
                }
                print("微博发送成功")
                
            }
        }
      
    }
    
}

extension ZJComposeViewController:UITextViewDelegate{
    
    
    func textViewDidChange(textView: UITextView) {

        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }
    
    //它还继承自uiscrollowView
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        self.composeTextView.resignFirstResponder()
    }
}
extension ZJComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{

    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        //这里可以得到我们选择的图片
//        print(image)
//        这里可以得到我们的composePictureView,可以直接调用addImage的方法
        //可以将选择的图片传递个PictureView
        //歘照片之前进行压缩
        
        
//        //压缩图片的另一宗方法
//        let imagedata = UIImageJPEGRepresentation(image, 0.2)
//        
//        let image = UIImage(data: imagedata!)
//        //然后写入数据
//        imagedata?.writeToFile(<#T##path: String##String#>, atomically: <#T##Bool#>)
        composePictureView.addImages(smallPicture(600, image: image))
//       composePictureView.addImages(image!)
        
        picker.dismissViewControllerAnimated(false, completion: nil)
        
    }
    
    //压缩图片方法之一:
    func smallPicture(width:CGFloat,image:UIImage)->UIImage{
        
        
        if width > image.size.width{
            
            return image
        }
        //否则对图片进行压缩
        let height = width * image.size.height / image.size.width
        
        let size = CGSize(width: width, height: height)
        //开启图形上下文
        UIGraphicsBeginImageContext(size)
        
        image.drawInRect(CGRect(origin: CGPoint(x: 0, y: 0), size: size))
        
        let result = UIGraphicsGetImageFromCurrentImageContext()
        
        //关闭图片上下文
        UIGraphicsEndImageContext()
        
         return result
        
    }
    
}



//按钮的点击事件
extension ZJComposeViewController{
    
    func selectImages(){
        
        
        
        //为了获取选择的图片,实现UIImagePickerController的代理方法
        picker.delegate = self
        
        presentViewController(picker, animated: true, completion: nil)
        
        
        
    }
    
    func selctedKeyBoard(){
        
        //系统自身的键盘
        if composeTextView.inputView == nil{
           
            composeTextView.inputView = emtionView
            
            
            composeToolBar.isEmotion = false
            
        }else{
          //自定义的键盘
            composeTextView.inputView = nil
            
            composeToolBar.isEmotion = true

        }
        
        // 刷新inputView
        composeTextView.reloadInputViews()
        
        //点击按钮的时候使composeTextView成为第一相相应着
        
        composeTextView.becomeFirstResponder()
    }
}